『Haskellの代数的構造入門 半群・モノイド・環とは何か?』
Haskellでマグマ・半群・環を定義していってる記事
code:memo.hs
class Magma a where
(<>) :: = a -> a -> a
-- 普通に定義してしまうと
instance Magma Integer where
(<>) = (+)
instance Magma Bool where
(<>) = (&&)
-- このままだと掛け算が定義できない。
-- Haskellではnewtypeで定義する
-- Sum, Product
newtype Sum a = Sum {
unSum :: a
} deriving (Show, Eq, Enum)
newtype Product a = Product {
unProduct :: a
} deriving (Show, Eq, Enum)
deriving instance Num a => Num (Sum a)
deriving instance Num a => Num (Product a)
instance Num a => Magma (Sum a) where
(<>) = (+)
instance Num a => Magma (Product a) where
(<>) = (*)
-- And, Or
newtype And a = And deriving (Show, Eq)
newtype Or a = OR deriving (Show, Eq)
instance Num a => Magma (And a) where
(<>) = (&&)
instance Num a => Magma (Or a) where
(<>) = (||)